<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            placeholder="请输入内容"
            v-model="queryinfo.query"
            clearable
            @clear="getUserList()"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUserList()"
            ></el-button> </el-input
        ></el-col>
        <el-col :span="6">
          <el-button type="primary" @click="dialogVisible = true"
            >添加用户</el-button
          ></el-col
        >
      </el-row>
      <el-table :data="userlist" :border="true" stripe>
        <el-table-column type="index" label="id"> </el-table-column>
        <el-table-column prop="username" label="姓名"> </el-table-column>
        <el-table-column prop="email" label="邮箱"> </el-table-column>
        <el-table-column prop="mobile" label="电话"> </el-table-column>
        <el-table-column prop="role_name" label="角色"> </el-table-column>
        <el-table-column label="状态">
          <template v-slot="scope">
            <el-switch
              v-model="scope.row.mg_state"
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="userStateChanges(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template v-slot="scope">
            <el-tooltip effect="dark" content="编辑信息" placement="top-start">
              <el-button
                type="primary"
                icon="el-icon-edit"
                circle
                size="mini"
                @click="showeditdialog(scope.row.id)"
              ></el-button>
            </el-tooltip>
            <el-tooltip effect="dark" content="分配角色" placement="top-start">
              <el-button
                type="warning"
                icon="el-icon-star-off"
                circle
                size="mini"
                @click="setrole(scope.row)"
              ></el-button>
            </el-tooltip>
            <el-tooltip effect="dark" content="删除信息" placement="top-start">
              <el-button
                type="danger"
                icon="el-icon-delete"
                circle
                size="mini"
                @click="removeuser(scope.row.id)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage4"
        :page-sizes="[1, 2, 3, 4]"
        :page-size="10"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
    <!-- 提示框 -->
    <el-dialog
      title="添加用户"
      :visible.sync="dialogVisible"
      width="50%"
      @close="dialogclose"
    >
      <el-form
        :model="addForm"
        :rules="addrules"
        ref="addFormref"
        label-width="100px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号码" prop="tel">
          <el-input v-model="addForm.tel"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="adduser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑用户信息 -->
    <el-dialog title="修改用户" :visible.sync="editdialogVisible" width="50%">
      <el-form
        :model="editFrom"
        ref="editFromruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="用户名">
          <el-input v-model="editFrom.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="editFrom.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号码">
          <el-input v-model="editFrom.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="edituserinfo">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配角色 -->
    <el-dialog
      title="分配角色"
      :visible.sync="setroledialogVisible"
      width="50%"
      @close="setroleclose"
    >
      <div>
        <p>姓名：{{ userinfo.username }}</p>
        <p>当前的角色：{{ this.userinfo.role_name }}</p>
        <p>
          分配角色：
          <el-select v-model="rolevalue" placeholder="请选择">
            <el-option
              v-for="item in rolelist"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setroledialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saverole">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    var checkemail = (rule, value, callback) => {
      const email =
        /^([A-Za-z0-9_\-\.\u4e00-\u9fa5])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,8})$/;
      if (email.test(value)) {
        return callback();
      }
      callback(new Error("邮箱不对"));
    };
    var checketel = (rule, value, callback) => {
      const tel = /^(\+?0?86\-?)?1[3-9]\d{9}$/;
      if (tel.test(value)) {
        return callback();
      }
      callback(new Error("手机号码不对"));
    };
    return {
      queryinfo: {
        query: "",
        pagenum: 1,
        pagesize: 4,
      },
      userlist: [],
      total: 0,
      dialogVisible: false,
      addForm: {
        username: "",
        password: "",
        email: "",
        tel: "",
      },
      addrules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 3, max: 5, message: "长度在 3 到 5 个字符", trigger: "blur" },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 3, max: 6, message: "长度在 3 到 6 个字符", trigger: "blur" },
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkemail, trigger: "blur" },
        ],
        tel: [
          { required: true, message: "请输入手机号码", trigger: "blur" },
          { validator: checketel, trigger: "blur" },
        ],
      },
      editdialogVisible: false,
      editFrom: {},
      setroledialogVisible: false,
      userinfo: {},
      rolelist: [],
      rolevalue: "",
    };
  },
  created() {
    this.getUserList();
    // console.log(this.userlist);
  },
  methods: {
    async getUserList() {
      const { data: res } = await this.$http.get("users", {
        params: this.queryinfo,
      });
      // console.log(res);
      // if (res.data.meta.status !== 200)
      //   return this.$message.error("获取用户列表失败");
      this.userlist = res.data.users;
      this.total = res.data.total;
    },
    //页数
    handleSizeChange(newpage) {
      // console.log("111" + newpage);
      this.queryinfo.pagenum = newpage;
      this.getUserList();
    },
    //每页的数据
    handleCurrentChange(newsize) {
      // console.log("222" + newsize);
      this.queryinfo.pagesize = newsize;
      this.getUserList();
    },
    //更新用户状态
    async userStateChanges(userinfo) {
      // console.log(userinfo);
      const { data: res } = await this.$http.put(
        `users/${userinfo.id}/state/${userinfo.mg_state}`
      );
      // console.log(res);
      if (res.meta.status !== 200) {
        userinfo.mg_state = !userinfo.mg_state;
        return this.$message.error("用户更新失败");
      }
      this.$message.success("用户更新成功");
    },
    dialogclose() {
      this.$refs.addFormref.resetFields();
    },
    //添加用户
    adduser() {
      this.$refs.addFormref.validate(async (valid) => {
        if (!valid) return;
        const { data: res } = await this.$http.post("users", this.addForm);
        if (res.meta.msg !== 201) {
          this.$message.error("添加用户失败");
        }
        this.$message.success("添加用户成功");
        this.dialogVisible = false;
        this.getUserList();
      });
    },
    async showeditdialog(id) {
      // console.log(id);
      const { data: res } = await this.$http.get(`users/${id}`);
      this.editFrom = res.data;
      this.editdialogVisible = true;
    },
    async edituserinfo() {
      const { data: res } = await this.$http.put(`users/${this.editFrom.id}`, {
        email: this.editFrom.email,
        mobile: this.editFrom.mobile,
      });
      this.editdialogVisible = false;
      this.getUserList();
      this.$message.success("编辑成功");
    },
    async removeuser(id) {
      //确认删除会显示confirm
      const result = await this.$confirm(
        "此操作将永久删除该文件, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      if (result !== "confirm") {
        return this.$message.info("已取消删除");
      }
      const { data: res } = await this.$http.delete(`users/${id}`);
      // console.log(res);
      if (res.meta.status !== 200) {
        return this.$message.error("删除用户失败");
      }
      this.$message.success("删除用户成功");
      this.getUserList();
    },
    // 分配角色
    async setrole(userinfo) {
      this.userinfo = userinfo;
      const { data: res } = await this.$http.get("roles");
      this.rolelist = res.data;
      this.setroledialogVisible = true;
    },
    async saverole() {
      const { data: res } = await this.$http.put(
        `users/${this.userinfo.id}/role`,
        {
          rid: this.rolevalue,
        }
      );
      if (res.meta.status !== 200) {
        return this.$message.error("分配失败");
      }
      this.$message.success("分配成功");
      this.getUserList;
      this.setroledialogVisible = false;
    },
    setroleclose() {
      this.rolevalue = "";
    },
  },
};
</script>

<style></style>
